﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace FlyingEye.HttpServices
{
    public class NotificationMessage
    {
        public bool ToUsers { get; set; }

        public List<string> Users { get; set; }

        public string Message { get; set; }

#pragma warning disable CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
        private NotificationMessage()
#pragma warning restore CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
        {
        }

        public static NotificationMessage GetGroupMessage(string message)
        {
            return new NotificationMessage() { ToUsers = false, Message = message };
        }

        public static NotificationMessage GetUserMessage(string message, List<string> users)
        {
            if (!users.Any())
            {
                throw new ArgumentException("用户列表不能为空", nameof(users));
            }

            return new NotificationMessage() { ToUsers = true, Message = message, Users = users };
        }
    }

    public class ComeNotificationService
    {
        private readonly HttpClientService _httpClientService;

        private readonly ApplicationOptions _applicationOptions;

        private readonly ILogger<ComeNotificationService> _logger;

        public ComeNotificationService(
            HttpClientService httpClientService,
            IOptions<ApplicationOptions> applicationOptions,
            ILogger<ComeNotificationService> logger)
        {
            _httpClientService = httpClientService;
            _applicationOptions = applicationOptions.Value;
            _logger = logger;
        }

        public async Task PostMessage(string message)
        {
            var groupMessage = NotificationMessage.GetGroupMessage(message);
            try
            {
                await _httpClientService.PostAsync<NotificationMessage>(
                $"{_applicationOptions.HttpBaseUrl}/api/device-app-service/v1.0/admin-messages",
                groupMessage);
            }
            catch (Exception err)
            {
                _logger.LogError(err, "COM 消息通知错误");
            }
        }
    }
}
